import React, { useEffect } from 'react';
import { Modal, Button } from 'antd';
import styled from '@emotion/styled';
import useSyncState from '../hooks/useSyncState';
import ObserverVideo from './ObserverVideo';
import Message from '@/utils/message';
import { useMenuContext } from '../Context/MenuContext';
import TTSVideo from './TTSVideoItem';
import { useTranslation } from 'react-i18next';

interface ServiceMonitoringProps {
	handleOk: () => void;
	handleCancel: () => void;
	isModalOpen: boolean;
	token: string;
}

const ServiceMonitoringContainer = styled(Modal)`
	top: calc(50% - 321px);
	.ant-modal-footer {
		text-align: center;
		padding: 20px 16px;
	}
`;

const JoinSessionBtn = styled(Button)``;

const TTSContainer = styled.div`
	display: none;
`;

const ServiceMonitoring = (props: ServiceMonitoringProps) => {
	const { t } = useTranslation();
	const { handleOk, handleCancel, isModalOpen, token } = props;
	const { setServiceMonitoring } = useMenuContext();
	const [remoteStream, setRemoteStream] = useSyncState<any>([]);
	const IRtc = ivcs.IRtc;
	const [irtcClient, setIRtcClient] = useSyncState<any>(null);

	const [substreamSuccess, setSubStreamSuccess] = useSyncState<boolean>(false);

	const [TTSStream, setTTSStream] = useSyncState<any>([]);

	const [renderTTSStream, setRenderTTSStream] = useSyncState<any>([]);

	useEffect(() => {
		let { ConferenceClient } = IRtc.Conference;
		let turnserverUrl = '';
		let turnserverCredential = '';
		let turnserverUsername = '';
		let ccOptions = {
			rtcConfiguration: {
				iceServers: [{}]
			}
		};
		let irtcClient = new ConferenceClient();
		setIRtcClient(irtcClient);
		if (token) {
			join();
		}
		return () => {
			leave();
		};
	}, []);

	const join = async () => {
		try {
			const data = await irtcClient().join(token);
			console.log('join success', data);
			const TTSStream = data.remoteStreams.filter((stream: any) => {
				if (stream.attributes && stream.attributes.type && stream.attributes.type.indexOf('tts') > -1) {
					return stream;
				}
			});
			setTTSStream(TTSStream);
			const streams = data.remoteStreams.filter((stream: any) => {
				if (stream.origin) {
					if (
						stream.attributes &&
						stream.attributes.type &&
						stream.attributes.type.indexOf('screen') === -1 &&
						stream.attributes.type.indexOf('recordScreen') === -1 &&
						stream.attributes.type.indexOf('tts') === -1 && 
						stream.attributes.type.indexOf('recordScreen-Regional') === -1
					) {
						return stream;
					} else if (stream.attributes && stream.attributes && stream.attributes.origin && stream.attributes.origin === 'bizbot') {
						return stream;
					}
				}
			});
			setRemoteStream(streams);
			remoteStream().forEach((item: any) => {
				streamEndEvent(item);
				streamUpdateEvent(item);
			});
			addclientEvent(irtcClient());
		} catch (error) {
			console.log(error, 'join error');
		}
	};

	const addclientEvent = (IRtcClient: any) => {
		let streamaddedListener = (eve: any) => {
			let stream = eve.stream;
			console.log('add stream');
			console.log(stream);
			if (stream.origin) {
				if (
					stream.attributes &&
					stream.attributes.type &&
					stream.attributes.type &&
					stream.attributes.type.indexOf('screen') === -1 &&
					stream.attributes.type.indexOf('recordScreen') === -1 &&
					stream.attributes.type.indexOf('tts') === -1 && 
					stream.attributes.type.indexOf('recordScreen-Regional') === -1
				) {
					setRemoteStream([...remoteStream(), stream]);
					remoteStream().forEach((item: any) => {
						streamEndEvent(item);
						streamUpdateEvent(item);
					});
				} else if (stream.attributes && stream.attributes && stream.attributes.origin && stream.attributes.origin === 'bizbot') {
					setRemoteStream([...remoteStream(), stream]);
					remoteStream().forEach((item: any) => {
						streamEndEvent(item);
						streamUpdateEvent(item);
					});
				} else if (stream.attributes && stream.attributes.type && stream.attributes.type.indexOf('tts') > -1) {
					setTTSStream([...TTSStream(), stream]);
					TTSStream().forEach((item: any) => {
						streamEndEvent(item);
						streamUpdateEvent(item);
					});
				}
			}
		};
		let participantjoinedListener = (eve: any) => {
			console.log('new participant joined:', eve);
		};

		let messagereceivedListener = (eve: any) => {
			console.log('new message received: ', eve);
		};

		let serverdisconnectedListener = () => {
			console.log('server disconnected');
			setServiceMonitoring(false);
			Message.normal(t('session-error-monitor-close'));
		};

		IRtcClient.addEventListener('streamadded', streamaddedListener);
		IRtcClient.addEventListener('participantjoined', participantjoinedListener);
		IRtcClient.addEventListener('messagereceived', messagereceivedListener);
		IRtcClient.addEventListener('serverdisconnected', serverdisconnectedListener);
	};

	const streamEndEvent = (stream: any) => {
		let enedListener = (event: any) => {
			console.log(`remote stream ${stream.id} is ended`);
			let streams = [...remoteStream()];
			streams = streams.filter(item => item.id !== stream.id);
			setRemoteStream(streams);
			if (remoteStream().length === 0 && isModalOpen) {
				setServiceMonitoring(false);
				Message.warning(t('session-end-monitor-close'));
			}
		};
		stream.addEventListener('ended', enedListener);
	};

	const streamUpdateEvent = (stream: any) => {
		let streamUpdatedEvent = (event: any) => {
			console.log('stream update eventInfo:', event);
		};
		stream.addEventListener('updated', streamUpdatedEvent);
	};

	const leave = () => {
		irtcClient().clearEventListener('streamadded');
		irtcClient().clearEventListener('participantjoined');
		irtcClient().clearEventListener('messagereceived');
		irtcClient().clearEventListener('serverdisconnected');
		irtcClient().clearEventListener('ended');
		// self.$toast('成功离开');
		remoteStream().forEach((item: any) => {
			window.clearInterval(item.intervalId);
		});
		irtcClient() &&
			irtcClient()
				.leave()
				.then(
					() => {
						setRemoteStream([]); //删除已经订阅的任何流
						console.log('this.irtcClient leave success');
					},
					(err: any) => {
						//self.$toast('离开失败'+err);
						console.log('this.irtcClient leave failed: ', err);
					}
				);
	};

	return (
		<ServiceMonitoringContainer
			destroyOnClose={true}
			keyboard={false}
			maskClosable={false}
			title={t('service-monitor')}
			open={isModalOpen}
			onCancel={handleCancel}
			footer={[
				<JoinSessionBtn onClick={handleOk} key="joinSession" type="primary">
					{t('join-session')}
				</JoinSessionBtn>
			]}
		>
			<ObserverVideo remoteStream={remoteStream()} substreamSuccess={substreamSuccess()} irtcClient={irtcClient()} />
			<TTSContainer>
				{TTSStream().map((item: any, index: number) => {
					return <TTSVideo key={index} irtcClient={irtcClient()} setRenderTTSStream={setRenderTTSStream} renderTTSStream={renderTTSStream()} streamId={item.id} stream={item} />;
				})}
			</TTSContainer>
		</ServiceMonitoringContainer>
	);
};

export default ServiceMonitoring;
